package com.eptok.gw.szcups.cups.busi.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ys8583.parse.IOMessage;

import com.eptok.gw.szcups.common.GateWayConstant;
import com.eptok.gw.szcups.common.KeyContainer;
import com.eptok.gw.szcups.common.PropertyLoader;
import com.eptok.gw.szcups.cups.CupsMessageControl;
import com.eptok.gw.szcups.cups.busi.CupsBusiInterface;
import com.eptok.gw.szcups.cups.message.MacGenerator;
import com.eptok.gw.szcups.hsm.HsmService;
import com.eptok.gw.szcups.monitor.Monitor;
import com.eptok.gw.szcups.socket.client.factory.ClientFactory;
import com.solab.iso8583.common.ByteUtil;

/**
 * 重置密钥
 * 
 *@author:heqishan, Email:heqishan@gmail.com
 *2013-3-20 下午03:39:35
 */
public class ResetKeyBusiImpl implements CupsBusiInterface {
	
	private static final Logger log = LoggerFactory.getLogger(ResetKeyBusiImpl.class);

	public void dobusiness(IOMessage ioMessage){
		try {
			ioMessage.setRspMap(ioMessage.getReqMap());
			ioMessage.setRspMessageID((String)ioMessage.getReqMessageID());
			//解出mak
			byte[] field96 = (byte[])ioMessage.getReqMesField(96);
			String field96_hex = ByteUtil.BinaryToHexString(field96);
			String zak_zmk = new HsmService().zak_zmk2lmk(KeyContainer.getInstance().getMerCupsZmk(),
					field96_hex, "");
			
			String srcField128 = ByteUtil.BinaryToHexString((byte[])ioMessage.getReqMesField(128));
			
			//验证mac
			String hex_mac = new MacGenerator().generateMarchantMac(ioMessage,zak_zmk);
			if(!hex_mac.equals(srcField128)){
				throw new Exception("验证mac失败：" + hex_mac);
			}
			IOMessage iomes = new IOMessage(GateWayConstant.MSG_CODE_TEMPLATE_ID);
			iomes.setRspMap(ioMessage.getReqMap());			
			iomes.setRspMessageID(GateWayConstant.MSG_CODE_SING_RESET_RSP);
			iomes.removeField(96);
			iomes.setRspField(39, "00");
			new MacGenerator().generateMarchantMac(iomes,zak_zmk);
			
			String field53 = (String)iomes.getRspField(53);
			char keyType = field53.charAt(0);		//为1表示PIK，为2表示MAK
			if('1' == keyType){
//				//TODO 需要将hsmService的zpk转换方法改为公共（渠道是des，sp服务提供商是3des）
				//TODO 因为商户报文没有涉及到pin加密的，所以暂时不用进行pin转换
//				String zpk_zmk = new HsmService().zpk_zmk2lmk(KeyContainer.getInstance().getMerCupsZmk(), 
//						field96_hex, HsmService.HSM_3DESKEY_MODE,"");
//				KeyContainer.getInstance().setMerZPK(zpk_zmk);
			}else if('2' == keyType){
				KeyContainer.getInstance().setMerZAK(zak_zmk);
				Monitor.getInstance().setMerchantHasKey(true);
			}else{
				throw new Exception("53#安全控制信息未识别类型：" + keyType);
			}
			
			PropertyLoader.getInstance().storeConfig();
			iomes.createResponseMsg();
			ClientFactory.getInstance().sendMessage(CupsMessageControl.PASSIVE_MERCHAN_CLIENT_KEY, iomes);
		}catch (Exception e) {
			log.error("商户重置密钥失败",e);
		}
	}

}
